package com.googlecode.jlogalizerweb.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * This program is for internal purposes only. Saves the need to login to the actual instance
 *
 */
public class ProcessController implements Controller{

/*
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String command = request.getParameter("commandBox");
		
		
		File targetFile = new File("/tmp", "processoutput.log");
		
		List<String> commandList = new ArrayList<String>();
		commandList.add(command);

		ProcessBuilder builder = new ProcessBuilder(commandList);
	    //builder.directory(new File("/Users/Jason"));
	    
		final Process process = builder.start();
		InputStream inputStream = process.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
		BufferedReader buffReader = new BufferedReader(inputStreamReader);
		String line;
		while ((line = buffReader.readLine()) != null) {
			System.out.println(line);
			FileAppendUtils.appendToFile(line, targetFile);
		}
		System.out.println("command executed !!!");
		
	
		return null;
	
	}
	*/
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		System.out.println("In process controller");
		String command = request.getParameter("commandBox");

		File targetFile = new File("/tmp", "processoutput.log");
		
		
		PrintWriter printWriter=new PrintWriter(targetFile);

		String line;
		Process p = Runtime.getRuntime().exec(command);
		BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
		while ((line = input.readLine()) != null) {
			System.out.println("Line is 123:" + line);
			//FileAppendUtils.appendToFile(line, targetFile);
			printWriter.println(line);
			printWriter.flush();
		}
		printWriter.close();
		input.close();

		System.out.println("command executed !!!");

		return null;

	}
	
}
